﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TinyToolKit.FSM;

namespace TinyToolKit.Demo
{
    public class PatrolState : FsmState<Enemy>
    {
        public float rotateSmooth = 3;
        public float patrolSpeed = 5;

        private Transform enemy;
        private Transform player;
        private List<Transform> pathsList = new List<Transform>();
        private int index = 0;
        private float detectRadius;

        protected override void OnInit()
        {
            base.OnInit();
            enemy = FSM.GetData<Transform>(TinyDefine_Demo.FSM_EnemyTF);
            detectRadius = FSM.GetData<float>(TinyDefine_Demo.FSM_DetectedRadius);
            patrolSpeed = FSM.GetData<float>(TinyDefine_Demo.FSM_EnemySpeed);
            player = GameObject.Find("Player").transform;
            Transform pathRoot = GameObject.Find("PathRoot").transform;
            foreach (Transform pathPoint in pathRoot)
            {
                pathsList.Add(pathPoint);
            }
        }

        protected override void OnAct()
        {
            base.OnAct();

            Vector3 forward = pathsList[index].position - enemy.position;
            forward = new Vector3(forward.x, 0, forward.z);
            Quaternion targetQuaternion = Quaternion.LookRotation(forward, Vector3.up);
            enemy.rotation = Quaternion.Slerp(enemy.rotation, targetQuaternion, Time.deltaTime * rotateSmooth);
            enemy.Translate(Vector3.forward * Time.deltaTime * patrolSpeed);
            if (Vector3.Distance(enemy.position, pathsList[index].position) < 2f)
            {
                index++;
                index %= pathsList.Count;
            }

            if (Vector3.Distance(enemy.position, player.position) < detectRadius)
            {
                this.FSM.ChangeState(typeof(ChaseState));
            }
        }
    }
}

